<template>
    <div id='container'></div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { Chart } from '@antv/g2'

let chart

onMounted(() => {
    chart = new Chart({
        container,
        autoFit: true,
    });
    chart
        .title('发散条形图')
        .coordinate({
            transform: [
                {
                    type: 'transpose'
                }
            ]
        })
        .interval()
        .data({
            type: 'fetch',
            value: '/os/bmw-prod/87b2ff47-2a33-4509-869c-dae4cdd81163.csv',
            transform: [
                {
                    type: 'filter',
                    callback:(item) => item.year === 2000
                }
            ]
        })
        .encode('x', 'age')
        .encode('y', (d) => (d.sex === 1 ? -d.people : d.people))
        .encode('color', 'sex')
        .scale('color', {
            type: 'ordinal'
        })
        .scale('x', {range: [1, 0]})
        .axis('y', {labelFormatter: '~s', title: 'people number'})
        .legend('color', { labelFormatter:(d) => (d === 1 ? 'Male' : 'Female')})
        .tooltip((d) => ({
            value: d.people,
            name: d.sex === 1 ? 'Male' : 'Female'
        }))

    chart.render();
});

// 销毁
onUnmounted(() => {
    chart.destroy();
    chart = null;
});
</script>

<style lang='less' scoped>
#container {
    width: 800px;
    height: 400px;
}
</style>